import * as XLSX from 'xlsx'
import type { UploadFile } from 'ant-design-vue'
import { saveAs } from 'file-saver'
import type { ExcelItem } from '../types/attendance'

/**
 * 将Excel解析成JSON
 * @param file
 * @return 数组: ExcelItem[]
 */
export function AnalyzeExcel(file: UploadFile): Promise<ExcelItem[]> {
  return new Promise((resolve, reject) => {
    // 创建实例
    const fileReader = new FileReader()
    // 处理文件内容
    fileReader.onload = (e) => {
      const data = new Uint8Array(e.target?.result as ArrayBuffer)
      const workBook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workBook.SheetNames[0]
      const workSheet = workBook.Sheets[firstSheetName]
      const workBookData: ExcelItem[] = XLSX.utils.sheet_to_json(workSheet, { header: 'A', raw: false })
      resolve(workBookData)
    }
    fileReader.onerror = (e) => {
      reject(e)
    }
    // 读取二进制流文件内容
    fileReader.readAsArrayBuffer(file as any)
  })
}

/**
 * 导出EXCELEXCEL文件
 * @param data 数组
 * @param fileName 文件名
 */
export function downloadExcel(data: Array<any>, fileName: string): void {
  // 将数据转换为xlsx工作表
  const worksheet = XLSX.utils.json_to_sheet(data)

  // 创建工作簿并添加工作表
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成EXCEL文件
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })

  // 使用blob和saveAs下载文件
  const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' })
  saveAs(dataBlob, `${fileName}.xlsx`)
}
